const Team = require('../models/Team');
const User = require('../models/User');
const { successResponse, errorResponse, paginationResponse } = require('../utils/response');
const logger = require('../utils/logger');

// 获取团队列表
exports.getTeams = async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const skip = (page - 1) * limit;
    const sort = req.query.sort || 'createdAt';
    const order = req.query.order === 'asc' ? 1 : -1;
    
    // 查询条件
    const filter = {};
    if (req.query.name) {
      filter.name = { $regex: req.query.name, $options: 'i' };
    }
    if (req.query.status) {
      filter.status = req.query.status;
    }
    if (req.query.leader) {
      filter.leader = req.query.leader;
    }

    // 查询团队总数
    const total = await Team.countDocuments(filter);
    
    // 查询团队列表
    const teams = await Team.find(filter)
      .populate('leader', 'username name avatar')
      .populate('members', 'username name avatar')
      .sort({ [sort]: order })
      .skip(skip)
      .limit(limit);

    return paginationResponse(res, teams, page, limit, total);
  } catch (error) {
    logger.error(`获取团队列表失败: ${error.message}`);
    return errorResponse(res, '获取团队列表失败', 500);
  }
};

// 获取单个团队
exports.getTeam = async (req, res) => {
  try {
    const team = await Team.findById(req.params.id)
      .populate('leader', 'username name avatar')
      .populate('members', 'username name avatar');
    
    if (!team) {
      return errorResponse(res, '团队不存在', 404);
    }

    return successResponse(res, team, '获取团队成功');
  } catch (error) {
    logger.error(`获取团队失败: ${error.message}`);
    return errorResponse(res, '获取团队失败', 500);
  }
};

// 创建团队
exports.createTeam = async (req, res) => {
  try {
    const { name, description, leader, members = [], status } = req.body;

    // 验证团队负责人是否存在
    const leaderExists = await User.findById(leader);
    if (!leaderExists) {
      return errorResponse(res, '团队负责人不存在', 400);
    }

    // 如果提供了成员列表，验证所有成员是否存在
    if (members.length > 0) {
      const membersExist = await User.countDocuments({
        _id: { $in: members },
      });

      if (membersExist !== members.length) {
        return errorResponse(res, '一个或多个团队成员不存在', 400);
      }
    }

    // 创建新团队
    const team = new Team({
      name,
      description,
      leader,
      members,
      status: status || 'active'
    });

    await team.save();
    
    // 获取包含详细信息的团队
    const populatedTeam = await Team.findById(team._id)
      .populate('leader', 'username name avatar')
      .populate('members', 'username name avatar');

    return successResponse(res, populatedTeam, '创建团队成功', 201);
  } catch (error) {
    logger.error(`创建团队失败: ${error.message}`);
    return errorResponse(res, '创建团队失败', 500);
  }
};

// 更新团队
exports.updateTeam = async (req, res) => {
  try {
    const { name, description, leader, status } = req.body;
    
    // 查找团队
    const team = await Team.findById(req.params.id);
    if (!team) {
      return errorResponse(res, '团队不存在', 404);
    }

    // 如果更新了负责人，验证负责人是否存在
    if (leader && leader !== team.leader.toString()) {
      const leaderExists = await User.findById(leader);
      if (!leaderExists) {
        return errorResponse(res, '团队负责人不存在', 400);
      }
      team.leader = leader;
    }

    // 更新团队信息
    if (name) team.name = name;
    if (description !== undefined) team.description = description;
    if (status) team.status = status;

    team.updatedAt = Date.now();
    await team.save();

    // 获取包含详细信息的团队
    const updatedTeam = await Team.findById(team._id)
      .populate('leader', 'username name avatar')
      .populate('members', 'username name avatar');

    return successResponse(res, updatedTeam, '更新团队成功');
  } catch (error) {
    logger.error(`更新团队失败: ${error.message}`);
    return errorResponse(res, '更新团队失败', 500);
  }
};

// 删除团队
exports.deleteTeam = async (req, res) => {
  try {
    const team = await Team.findById(req.params.id);
    if (!team) {
      return errorResponse(res, '团队不存在', 404);
    }

    await team.remove();
    return successResponse(res, null, '删除团队成功');
  } catch (error) {
    logger.error(`删除团队失败: ${error.message}`);
    return errorResponse(res, '删除团队失败', 500);
  }
};

// 添加团队成员
exports.addMember = async (req, res) => {
  try {
    const { userId } = req.body;
    const teamId = req.params.id;

    // 验证团队是否存在
    const team = await Team.findById(teamId);
    if (!team) {
      return errorResponse(res, '团队不存在', 404);
    }

    // 验证用户是否存在
    const user = await User.findById(userId);
    if (!user) {
      return errorResponse(res, '用户不存在', 404);
    }

    // 检查用户是否已经是团队成员
    if (team.members.includes(userId)) {
      return errorResponse(res, '用户已经是团队成员', 400);
    }

    // 添加成员
    team.members.push(userId);
    await team.save();

    // 获取包含详细信息的团队
    const updatedTeam = await Team.findById(team._id)
      .populate('leader', 'username name avatar')
      .populate('members', 'username name avatar');

    return successResponse(res, updatedTeam, '添加团队成员成功');
  } catch (error) {
    logger.error(`添加团队成员失败: ${error.message}`);
    return errorResponse(res, '添加团队成员失败', 500);
  }
};

// 移除团队成员
exports.removeMember = async (req, res) => {
  try {
    const { userId } = req.params;
    const teamId = req.params.id;

    // 验证团队是否存在
    const team = await Team.findById(teamId);
    if (!team) {
      return errorResponse(res, '团队不存在', 404);
    }

    // 检查用户是否是团队成员
    if (!team.members.includes(userId)) {
      return errorResponse(res, '用户不是团队成员', 400);
    }

    // 如果是团队负责人，不能移除
    if (team.leader.toString() === userId) {
      return errorResponse(res, '不能移除团队负责人', 400);
    }

    // 移除成员
    team.members = team.members.filter(memberId => memberId.toString() !== userId);
    await team.save();

    // 获取包含详细信息的团队
    const updatedTeam = await Team.findById(team._id)
      .populate('leader', 'username name avatar')
      .populate('members', 'username name avatar');

    return successResponse(res, updatedTeam, '移除团队成员成功');
  } catch (error) {
    logger.error(`移除团队成员失败: ${error.message}`);
    return errorResponse(res, '移除团队成员失败', 500);
  }
}; 